"use client"

import { useState, useEffect } from 'react';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from '@/components/ui/alert-dialog';
import { Skeleton } from '@/components/ui/skeleton';
import { Region } from '@/types/player';
import { getRegions, addRegion, updateRegion, deleteRegion } from '@/lib/data';
import { Plus, Trash2, Edit, Save, X } from 'lucide-react';

export default function RegionsManager() {
  const [regions, setRegions] = useState<Region[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [showAddForm, setShowAddForm] = useState(false);
  const [editingRegion, setEditingRegion] = useState<Region | null>(null);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [regionToDelete, setRegionToDelete] = useState<Region | null>(null);
  
  // 新地区表单
  const [newRegion, setNewRegion] = useState({
    name: '',
    color: '#6C87FF',
  });
  
  const loadRegions = async () => {
    try {
      setLoading(true);
      setError(null);
      const response = await fetch('/api/regions');
      if (!response.ok) {
        throw new Error('获取地区数据失败');
      }
      const data = await response.json();
      setRegions(data);
    } catch (err: any) {
      console.error('加载地区数据失败:', err);
      setError('无法加载地区数据，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadRegions();
  }, []);

  const handleAddSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!newRegion.name.trim()) {
      setError('地区名称不能为空');
      return;
    }
    
    try {
      const response = await fetch('/api/regions', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(newRegion),
      });
      
      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || '添加地区失败');
      }
      
      setShowAddForm(false);
      setNewRegion({ name: '', color: '#6C87FF' });
      loadRegions();
    } catch (err: any) {
      console.error('添加地区失败:', err);
      setError(err.message || '添加地区失败，请稍后重试');
    }
  };

  const handleEditSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!editingRegion || !editingRegion.name.trim()) {
      setError('地区名称不能为空');
      return;
    }
    
    try {
      const response = await fetch(`/api/region/${editingRegion.id}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          name: editingRegion.name,
          color: editingRegion.color
        }),
      });
      
      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || '更新地区失败');
      }
      
      setEditingRegion(null);
      loadRegions();
    } catch (err: any) {
      console.error('更新地区失败:', err);
      setError(err.message || '更新地区失败，请稍后重试');
    }
  };

  const handleOpenDeleteDialog = (region: Region) => {
    setRegionToDelete(region);
    setDeleteDialogOpen(true);
  };

  const handleDeleteRegion = async () => {
    if (!regionToDelete) return;
    
    try {
      const response = await fetch(`/api/region/${regionToDelete.id}`, {
        method: 'DELETE',
      });
      
      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || '删除地区失败');
      }
      
      setDeleteDialogOpen(false);
      setRegionToDelete(null);
      loadRegions();
    } catch (err: any) {
      console.error('删除地区失败:', err);
      setError(err.message || '删除地区失败，请稍后重试');
    }
  };

  return (
    <Card className="border border-gray-800 bg-[#1a1d24]">
      <CardHeader className="flex flex-row items-center justify-between">
        <div>
          <CardTitle>地区管理</CardTitle>
          <CardDescription>管理玩家的地区分类</CardDescription>
        </div>
        <Button 
          onClick={() => setShowAddForm(true)}
          className="bg-blue-600 hover:bg-blue-700"
          disabled={showAddForm}
        >
          <Plus className="h-4 w-4 mr-2" />
          添加地区
        </Button>
      </CardHeader>
      <CardContent>
        {error && (
          <div className="bg-red-500/20 border border-red-500 text-red-300 p-3 rounded mb-4">
            {error}
          </div>
        )}

        {showAddForm && (
          <form onSubmit={handleAddSubmit} className="mb-6 border border-gray-700 rounded-lg p-4">
            <h3 className="text-lg font-medium mb-4">添加新地区</h3>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
              <div className="space-y-2">
                <label className="text-sm text-gray-400">地区名称</label>
                <Input
                  value={newRegion.name}
                  onChange={(e) => setNewRegion({ ...newRegion, name: e.target.value })}
                  placeholder="输入地区名称"
                  className="bg-[#252a33] border-gray-700"
                />
              </div>
              <div className="space-y-2">
                <label className="text-sm text-gray-400">地区颜色</label>
                <div className="flex space-x-2">
                  <Input
                    type="color"
                    value={newRegion.color}
                    onChange={(e) => setNewRegion({ ...newRegion, color: e.target.value })}
                    className="w-12 h-10 p-1 bg-[#252a33] border-gray-700"
                  />
                  <Input
                    value={newRegion.color}
                    onChange={(e) => setNewRegion({ ...newRegion, color: e.target.value })}
                    placeholder="#RRGGBB"
                    className="flex-1 bg-[#252a33] border-gray-700"
                  />
                </div>
              </div>
            </div>
            <div className="flex justify-end space-x-2">
              <Button 
                type="button" 
                variant="outline" 
                onClick={() => {
                  setShowAddForm(false);
                  setNewRegion({ name: '', color: '#6C87FF' });
                }}
                className="border-gray-700"
              >
                <X className="h-4 w-4 mr-2" />
                取消
              </Button>
              <Button type="submit" className="bg-blue-600 hover:bg-blue-700">
                <Save className="h-4 w-4 mr-2" />
                保存
              </Button>
            </div>
          </form>
        )}

        {loading ? (
          <div className="space-y-2">
            {[1, 2, 3].map((i) => (
              <Skeleton key={i} className="h-12 w-full" />
            ))}
          </div>
        ) : regions && regions.length === 0 ? (
          <div className="text-center py-8 text-gray-500">
            暂无地区数据
          </div>
        ) : (
          <div className="space-y-2">
            {regions && regions.map((region) => (
              <div key={region.id} className="border border-gray-700 rounded-lg p-4">
                {editingRegion && editingRegion.id === region.id ? (
                  <form onSubmit={handleEditSubmit} className="space-y-4">
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                      <div className="space-y-2">
                        <label className="text-sm text-gray-400">地区名称</label>
                        <Input
                          value={editingRegion.name}
                          onChange={(e) => setEditingRegion({ ...editingRegion, name: e.target.value })}
                          placeholder="输入地区名称"
                          className="bg-[#252a33] border-gray-700"
                        />
                      </div>
                      <div className="space-y-2">
                        <label className="text-sm text-gray-400">地区颜色</label>
                        <div className="flex space-x-2">
                          <Input
                            type="color"
                            value={editingRegion.color}
                            onChange={(e) => setEditingRegion({ ...editingRegion, color: e.target.value })}
                            className="w-12 h-10 p-1 bg-[#252a33] border-gray-700"
                          />
                          <Input
                            value={editingRegion.color}
                            onChange={(e) => setEditingRegion({ ...editingRegion, color: e.target.value })}
                            placeholder="#RRGGBB"
                            className="flex-1 bg-[#252a33] border-gray-700"
                          />
                        </div>
                      </div>
                    </div>
                    <div className="flex justify-end space-x-2">
                      <Button 
                        type="button" 
                        variant="outline" 
                        onClick={() => setEditingRegion(null)}
                        className="border-gray-700"
                      >
                        <X className="h-4 w-4 mr-2" />
                        取消
                      </Button>
                      <Button type="submit" className="bg-blue-600 hover:bg-blue-700">
                        <Save className="h-4 w-4 mr-2" />
                        保存
                      </Button>
                    </div>
                  </form>
                ) : (
                  <div className="flex items-center justify-between">
                    <div className="flex items-center space-x-3">
                      <div 
                        className="w-6 h-6 rounded-full" 
                        style={{ backgroundColor: region.color }}
                      ></div>
                      <span className="font-medium">{region.name}</span>
                    </div>
                    <div className="flex space-x-2">
                      <Button 
                        variant="ghost" 
                        size="icon" 
                        onClick={() => setEditingRegion(region)}
                      >
                        <Edit className="h-4 w-4" />
                      </Button>
                      <Button 
                        variant="ghost" 
                        size="icon" 
                        onClick={() => handleOpenDeleteDialog(region)}
                        className="text-red-500 hover:text-red-700"
                      >
                        <Trash2 className="h-4 w-4" />
                      </Button>
                    </div>
                  </div>
                )}
              </div>
            ))}
          </div>
        )}
      </CardContent>

      <AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
        <AlertDialogContent className="bg-[#2a2e35] border-gray-700 text-white">
          <AlertDialogHeader>
            <AlertDialogTitle>确认删除地区?</AlertDialogTitle>
            <AlertDialogDescription className="text-gray-400">
              您确定要删除地区 "{regionToDelete?.name}" 吗？此操作可能影响已分配该地区的玩家。
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel className="bg-transparent border-gray-700">取消</AlertDialogCancel>
            <AlertDialogAction 
              onClick={handleDeleteRegion}
              className="bg-red-600 hover:bg-red-700 text-white"
            >
              确认删除
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </Card>
  );
} 